const express = require('express');
const router = express.Router();
const { getKnex } = require('../db/knex');
const Result = require('../utils/Result');

// 查询技术栈列表
router.get('/', async (req, res) => {
  try {
    const knex = getKnex();
    const list = await knex('technologies').select('*').orderBy('id');
    res.json(Result.success(list));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('查询技术栈失败'));
  }
});

// 新增技术栈
router.post('/', async (req, res) => {
  try {
    const knex = getKnex();
    const { name } = req.body;
    const [id] = await knex('technologies').insert({ name });
    res.json(Result.success({ id }, '技术栈添加成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('技术栈添加失败'));
  }
});

// 更新技术栈
router.put('/:id', async (req, res) => {
  try {
    const knex = getKnex();
    const id = req.params.id;
    const { name } = req.body;
    await knex('technologies').where({ id }).update({ name });
    res.json(Result.success(null, '技术栈更新成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('技术栈更新失败'));
  }
});

// 删除技术栈
router.delete('/:id', async (req, res) => {
  try {
    const knex = getKnex();
    const id = req.params.id;
    await knex('technologies').where({ id }).del();
    res.json(Result.success(null, '技术栈删除成功'));
  } catch (error) {
    console.error(error);
    res.json(Result.fail('技术栈删除失败'));
  }
});

module.exports = router;
